const Controller = require('egg').Controller

class HomeController extends Controller{
  async server(){
    const { ctx,app } = this

    const nsp = app.io.of('/')
    const message = ctx.args[0] || {}
    const socket = ctx.socket
    const client = socket.id

    try{
      const { target,payload } = message
      if(!target) return
      const msg = ctx.helper.parseMsg('server',payload,{ client,target })
      
      nsp.emit(target,msg)

    }catch(error){
      app.logger.error(error)
    }

  }
  async logout(){
    const { ctx,app } = this
  }
  async isLogin(){
    const { ctx,app } = this
    const message = ctx.args[0] || {}
    var userInfo = await app.redis.get("userInfo")
    //解析token

    var res = await ctx.service.admin.parseToken(userInfo)
    ctx.socket.emit('res',res)

    //用户退出的同时删除redis，token的数据
  }
  async loginGithub(){
    const { ctx,app } = this

    var code = ctx.query.code

    var state = ctx.query.state

    const githubConfig = {
      client_ID: "ddec6b18f5d9a6842502",
      client_Secret: "12fe3d3ba384bfbd7b5720efe35036ae366b6835",
      scope: "user",
      access_token_url: "https://github.com/login/oauth/access_token",
      user_info_url: "https://api.github.com/user",
      //redirect_uri:"http://127.0.0.1:7001/message/index",
      //auth_url:"https://github.com/login/oauth/authorize"
    }

    const result = await ctx.curl(githubConfig.access_token_url, {
      method: 'POST',
      contentType: "json",
      data: {
        client_id: githubConfig.client_ID,
        client_secret: githubConfig.client_Secret,
        code,
      },
      dataType: "json"
    })

    const userInfo = await ctx.curl(githubConfig.user_info_url, {
      method: "GET",
      dataType: "json",
      headers: {},
      data: {
        access_token: result.data.access_token,
        scope: "user"
      }
    })

    var res = ""
    if (userInfo.data.login) {
      res = userInfo.data.login + " " + userInfo.data.avatar_url

      //将第三方登录的用户映射到数据库中
      var obj = {
        uname: userInfo.data.login,
        avatar: userInfo.data.avatar_url,
        email: userInfo.data.blog
      }

      await ctx.service.user.saveGithubUser(obj)
    } else {
      res = "error"
    }

    var id = userInfo.data.login.id
    var time = 3600 * 24 * 30 //以为单位秒
    //var userInfo = res

    var token = await ctx.service.admin.getToken({
      _id: id,
      _userInfo: res
    }, time)

    // console.log(token)

    //await app.redis.set("userInfo",token,'EX',time)
    await app.redis.set("userInfo",token)

    //await app.redis.set("userInfo",res);

    await ctx.socket.emit('res',res)

  }
}

module.exports = HomeController

//数据共享在socket中行不通，只能使用redis，cookie只用于http协议，session是基于http协议的，websocket同样的支持cookie，因为websocket是基于http的
//长轮询comet
//窗口间通信postMessage
//设置过期时间以及数据之间的共享